import requests
import json
import hashlib
import time
import random

def translate(key):
	salt=str(int(time.time() * 1000) + random.randint(0, 10))

	sign = "fanyideskweb" + key + salt + "ebSeFb%=XZ%T[KZ)c(sy!"

	m = hashlib.md5() 
	m.update(sign.encode('utf-8')) 
	
	data={
		'i':key,
		'from':'en',
		'to':'zh-CHS',
		'smartresult':'dict',
		'client':'fanyideskweb',
		'salt':salt,
		'sign':m.hexdigest(),
		'doctype':'json',
		'version':'2.1',
		'keyfrom':'fanyi.web',
		'action':'FY_BY_REALTIME',
		'typoResult':'false',
	}
	headers = { 
		'Cookie': 'OUTFOX_SEARCH_USER_ID=-2022895048@10.168.8.76;', 
		'Referer': 'http://fanyi.youdao.com/', 
		'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; rv:51.0) Gecko/20100101 Firefox/51.0', 
	} 

	url="http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

	res=requests.post(url,data=data,headers=headers)

	html=res.content.decode("utf-8")

	result=json.loads(html)

	print("翻译结果：")
	print()

	print(result['translateResult'][0][0]['tgt'])

	for i in range(len(result['smartResult']['entries'])):
		s=result['smartResult']['entries'][i]
		s=s.replace("\n","")
		print(s)

	print()

if __name__ == '__main__':
	while True:
		key=input("请输入要翻译的单词：")
		if key=='q':
			break
		else:
			translate(key)